package com.ifnk.portaljava.dapWeb.socket;
/**
 * <p>Title: 向proxy发送命令的类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */

import com.ifnk.portaljava.dapWeb.common.MessageBean;
import com.ifnk.portaljava.dapWeb.common.Util;
import com.ifnk.portaljava.dapWeb.dapweb.Command;
import com.ifnk.portaljava.dapWeb.dataPacket.TypeDefine;
import flex.messaging.MessageBroker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.nio.file.ClosedWatchServiceException;
import java.util.Arrays;

public class CommandsendToProxy {
    private Log loger = LogFactory.getLog(CommandsendToProxy.class);
    private MessageBean messageBean = new MessageBean();

    public CommandsendToProxy() {
    }

    // 发送calltrace请求命令
    public void sendCallTraceStartCommand(SocketProperty sp, String clientId,
                                          String condition, String protocol, String svrlist) {

        Command command = createCommand(clientId, condition, protocol, svrlist);

        byte[] packet = new byte[1024];
        try {
            int len = command.EncodeWWWCTStartCommand(packet, packet.length,
                    TypeDefine.WWW_CT_START);
            // socket输入流线程
            SocketWriter writer = new SocketWriter(sp.getOut(), packet, len);
            writer.start();
            // 发送命令时向flex发送连接消息
            if (writer.isError()) {
                sendMessage("sendCallTraceCommandSuccess", false, false, clientId);
                loger.info("WebServer Send CallTraceStartCommand Success "
                        + " condition: " + condition + " protocol: " + protocol
                        + " svrlist：" + svrlist + " clientId:" + clientId);
            } else {
                sp.flag = writer.isError();
                sendMessage("sendCallTraceCommandFailed", false, true, clientId);
                loger.info("WebServer Send CallTraceStartCommand Failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            loger.error("WebServer Exception " + e.toString());
        }
    }

    // 发送cdrquery请求命令
    public void sendCDRQueryStartCommand(SocketProperty sp, String clientId,
                                         int starttime, int endtime, String protocol, String svrlist,
                                         String condition, int maxDataNumber) throws Exception {

        Command command = createCommand(clientId, condition, protocol, svrlist);
        command.setStartTime(starttime);
        command.setEndTime(endtime);
        command.setMaxDataNumber(maxDataNumber);

        byte[] packet = new byte[1024];
        int len = command.EncodeWWWCQStartCommand(packet, packet.length,
                TypeDefine.WWW_CQ_START);
        // socket输入流线程
        SocketWriter writer = new SocketWriter(sp.getOut(), packet, len);
        writer.start();
        // 发送命令时向flex发送连接消息
        if (writer.isError()) {
            sendMessage("sendCDRQueryCommandSuccess", false, false, clientId);
            loger.info("WebServer Send CDRQueryCommand Success " + " protocol:"
                    + protocol + " svrlist: " + svrlist + " condition: "
                    + condition + " starttime: " + starttime + " endtime"
                    + endtime + " clientId:" + clientId);
        } else {
            sp.flag = writer.isError();
            sendMessage("sendCDRQueryCommandFailed", false, true, clientId);
            loger.info("WebServer Send CDRQueryCommand Failed");
        }
    }

    // 发送cdrpkt详细信息的请求
    public void sendRawQueryCommand(SocketProperty sp, String opType,
                                    String requestDateFromProxyId, String clientId, byte protocol, int svr_id, int cdr_id, int ts_s,
                                    int ts_ns) throws Exception {
        byte[] rawquery = new byte[1024];
        Command command = new Command();
        command.setSessionId(requestDateFromProxyId);
        command.setChar_protocol(protocol);
        command.setSvrId(svr_id);
        command.setCdrId(cdr_id);
        command.setTs_s(ts_s);
        command.setTs_ns(ts_ns);
        int cmd = 0;
        if ("callTrace".equals(opType)) {
            cmd = TypeDefine.WWW_CT_RAW_QUERY;
        } else if ("query".equals(opType)) {
            cmd = TypeDefine.WWW_CQ_RAW_QUERY;
        }
        int len = command.EncodeRawQuery(rawquery, rawquery.length, cmd);
        // socket输出内容的线程
        SocketWriter writer = new SocketWriter(sp.getOut(), rawquery, len);
        writer.start();
        // 发送命令时向flex发送连接消息
        if (writer.isError()) {
            sendMessage("sendRawQueryCommandSuccess", false, false, clientId);
            loger.info("WebServer " + opType + " sendRawQueryCommand Success " + "optype: "
                    + opType + " protocol: " + protocol + " svr_id: " + svr_id
                    + " cdr_id: " + cdr_id + "ts_s: " + ts_s + "ts_ns: "
                    + ts_ns + " requestDateFromProxyId:" + requestDateFromProxyId + " clientId:" + clientId);
        } else {
            sp.flag = writer.isError();
            sendMessage("endRawQueryCommandFailed", false, true, clientId);
            loger.info("WebServer " + opType + " sendRawQueryCommand Failed ");
        }
    }

    // 发送stop命令
    public void sendStopCommand(SocketProperty sp, String opType,
                                String clientId) throws Exception {
        int cmd = 0;
        if ("callTrace".equals(opType)) {
            cmd = TypeDefine.WWW_CT_STOP;
        } else {
            cmd = TypeDefine.WWW_CQ_STOP;
        }
        byte[] packet = new byte[1024];
        Command command = new Command();
        command.setSessionId(clientId);
        int len = command.EncodeStopCommand(packet, packet.length, cmd);
        SocketWriter writer = new SocketWriter(sp.getOut(), packet, len);
        writer.start();
        // 发送命令时向flex发送连接消息
        if (writer.isError()) {
            sendMessage("sendStopCommandSuccess", false, false, clientId);
            loger.info("WebServer " + opType + " Send StopCommand Success" + " opType:" + opType
                    + " clientId:" + clientId);
        } else {
            sp.flag = writer.isError();
            sendMessage("sendStopCommandFailed", false, true, clientId);
            loger.info("WebServer " + opType + " Send StopCommand Failed");
        }
    }

    // 发送cdrpkt详细信息的请求 queryquery
	/*
	public void sendQueryQueryCommand(SocketProperty sp, String opType,
			String requestDateFromProxyId,String clientId, byte protocol, int svr_id, int cdrs[], int times[]
		) throws Exception {
		byte[] rawquery = new byte[1024];
		Command command = new Command();
		command.setSessionId(requestDateFromProxyId);
		command.setChar_protocol(protocol);
		command.setSvrId(svr_id);
		command.setCdrId(cdrs[0]);
		int cmd = 0;
		
		if ("query".equals(opType)) {
			cmd = TypeDefine.WWW_RQ_RAW_QUERY;
		}
		
		int len = command.EncodeQueryQuery(rawquery, rawquery.length, cmd, cdrs, times);
		// socket输出内容的线程
		
		SocketWriter writer = new SocketWriter(sp.getOut(), rawquery, len);
		writer.start();
		
		// 发送命令时向flex发送连接消息
		if (writer.isError()) {
			sendMessage("sendRawQueryQueryCommandSuccess", false, false, clientId);
			loger.info("WebServer " + opType + " sendRawQueryQueryCommand Success " + "optype: "
					+ opType + "\n\tprotocol: " + protocol + "\n\tsvr_id: " + svr_id +
					"\n\trequestDateFromProxyId: "+requestDateFromProxyId+"\n\tclientId: " + clientId);
		} else {
			sp.flag = writer.isError();
			sendMessage("endRawQueryCommandFailed", false, true, clientId);
			loger.info("WebServer " + opType + " sendRawQueryCommand Failed ");
		}
	}
	*/

    public String sendQueryQueryCommand(SocketProperty sp, String opType,
                                        String requestDateFromProxyId, String clientId, byte protocol, int svr_id, int[] zdrs
            , int startTime
    ) throws Exception {
        byte[] rawquery = new byte[1024];
        Command command = new Command();
        command.setSessionId(requestDateFromProxyId);
        command.setChar_protocol(protocol);
        command.setSvrId(svr_id);
        command.setCdrId(zdrs[0]);
        command.setTs_s(startTime);
        int cmd = 0;

        if ("query".equals(opType)) {
            cmd = TypeDefine.WWW_RQ_RAW_QUERY;
        } else if ("imsearch".equals(opType)) {
            cmd = TypeDefine.WWW_RQ_RAW_QUERY_IMSI_QUERY;
        }

        System.out.println("cmd = " + cmd);
        System.out.println("zdrs = " + Arrays.toString(zdrs));
        int len = command.EncodeQueryQuery(rawquery, rawquery.length, cmd, zdrs);
        System.out.println("rawquery = " + Arrays.toString(rawquery));
        System.out.println("len = " + len);
        // socket输出内容的线程

        SocketWriter writer = new SocketWriter(sp.getOut(), rawquery, len);
        writer.start();

        // 发送命令时向flex发送连接消息
        if (writer.isError()) {
            String message = "WebServer " + opType + " sendRawQueryQueryCommand Success " + "optype: "
                    + opType + "\n\tprotocol: " + protocol + "\n\tsvr_id: " + svr_id +
                    "\n\trequestDateFromProxyId: " + requestDateFromProxyId + "\n\tclientId: " + clientId;
            return message;
        } else {
            sp.flag = writer.isError();
            //sendMessage("endRawQueryCommandFailed", false, true, clientId);
            String message = "WebServer " + opType + " sendRawQueryCommand Failed ";
            throw new RuntimeException(message);
        }
    }


    private void sendMessage(String message, boolean stopFlag, boolean erorFlag,
                             String clientId) {
        messageBean.setMessage(message);
        messageBean.setStopFlag(stopFlag);
        messageBean.setErrorFlag(erorFlag);
        sendMessagtoFlex(messageBean, clientId);
    }

    private void sendMessagtoFlex(Object message, String clientId) {
        MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
        String subTopic = "KeepAlive" + clientId;
        Util.routeMessage(messageBroker, subTopic, clientId, message);
    }

    private Command createCommand(String clientId, String condition, String protocol, String svrlist) {
        Command command = new Command();
        command.setSessionId(clientId);
        command.setCondition(condition);
        command.setStr_protocol(protocol);
        command.setSvrList(svrlist);
        return command;
    }

}
